﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ENG.TeachersDiary.Model;

namespace ENG.TeachersDiary
{
  public partial class FrmStudents : Form
  {
    private ENG.TeachersDiary.Model.DiaryDB db = null;
    private Class currentClass = null;

    public FrmStudents()
    {
      InitializeComponent();
    }

    private void FrmStudents_Load(object sender, EventArgs e)
    {
      ReDB();
    }

    private void ReDB ()
    {
      db = Common.DBConn;
      currentClass = Common.GetCurrentClass(db);

      this.Text = Properties.Resources.StudentsOfTheClass + " " + currentClass.Title;

      studentBindingSource.DataSource = currentClass.Students;
    }

    private void grd_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
      db.SubmitChanges();
    }

    private void btnAddByText_Click(object sender, EventArgs e)
    {
      FrmInsertStudents f = new FrmInsertStudents();

      f.ShowDialog();

      if (f.DialogResult != System.Windows.Forms.DialogResult.OK) return;

      List<Model.Student> newStudents = f.GetNewStudents();

      //var db = Common.DBConn;

      foreach (Model.Student fItem in newStudents)
      {        
        fItem.Class = currentClass;
        fItem.IsVisible = true;        
      } // foreach (var fItem in news)

      db.Students.InsertAllOnSubmit(newStudents);
      db.SubmitChanges();

      ReDB();
    }

    private void grd_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
    {
      Model.Student st = (Model.Student)e.Row.DataBoundItem;

      if (st.Marks.Count > 0)
      {
        MessageBox.Show(Properties.Resources.StudentWithMarksCannotBeDeleted,
          Properties.Resources.ErrorDialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
        e.Cancel = true;
        return;
      }
      else
      {
        db.Students.DeleteOnSubmit(st);
        db.SubmitChanges();
      }
    }

    private void grd_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
    {
      e.Row.Cells[grd.GetPropertyRowIndex("IsVisible")].Value = true;
      e.Row.Cells[grd.GetPropertyRowIndex("ClassID")].Value = currentClass.ClassID;
    }
  }
}
